package com.jiuhaohealth.log.launcher.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.jiuhaohealth.log.launcher.conf.LauncherConfig;

public class LogSocketClient extends Thread {
	
	LauncherConfig launcherConfig = LauncherConfig.getInstance();
	
	private Socket socketClient;
	private PrintWriter out;
	private BufferedReader in;
	
	private boolean isAvailable = false;
	
	
	@Override
	public void run() {
		launcherConfig.debugMsg("已启动日志消费者进程.");
		//创建socket连接
		connectService();
		
		//启动恢复socket链接进程
		new Ambulance().start();
		
		//启动数据清洗线程
		new Flusher().start();
		
		//启动读取服务端返回信息线程
		new Remsger().start();
	}
	
	public void launch(String msg){
		if(isAvailable){
			out.println(msg);
		}
	}
	
	/**
	 * 创建socket连接
	 */
	private void connectService(){
		String host = launcherConfig.getAttr("host");
		int port = Integer.parseInt(launcherConfig.getAttr("port"));
		
		try {
			launcherConfig.debugMsg("正在连接到Socket server host："+host+" port："+port);
			socketClient = new Socket(host,port);
			socketClient.setKeepAlive(true);
			launcherConfig.debugMsg("成功创建Socket连接");
			out = new PrintWriter(socketClient.getOutputStream());
			in = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
			
			isAvailable = true;
		} catch (IOException e1) {
			launcherConfig.errorMsg("socket客户端创建失败", e1);
		}
	}
	
	private synchronized void flushData(){
		out.flush();
	}
	
	/**
	 * 处理缓冲区数据
	 * @author zhanggh@jiuhaohealth.com
	 * @hostname wow
	 *
	 */
	private class Flusher extends Thread{
		long interval = 2*1000;
		@Override
		public void run() {
			while(true){
				try {
					sleep(interval);
				} catch (InterruptedException e) {
				}
				flushData();
			}
		}
	}
	
	/**
	 * 读取服务端响应
	 * @author zhanggh@jiuhaohealth.com
	 * @hostname wow
	 *
	 */
	private class Remsger extends Thread{
		@Override
		public void run() {
			while(true){
				try {
					String remsg = in.readLine();
					if(!"OK".equals(remsg) && isAvailable){
						System.out.println(remsg);
						isAvailable = false;
					}
				} catch (Exception e) {
					if(isAvailable){
						launcherConfig.errorMsg("", e);
						isAvailable = false;
					}
				}
			}
		}
	}
	
	/**
	 * 当socket连接不可用时   重新连接  检查间隔时间10秒
	 * @author zhanggh@jiuhaohealth.com
	 * @hostname wow
	 *
	 */
	private class Ambulance extends Thread{
		long interval = 10*1000;
		
		@Override
		public void run() {
			while(true){
				try {
					sleep(interval);
				} catch (InterruptedException e) {
				}
				if(!isAvailable){
					connectService();
				}
			}
		}
	}
}
